import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:proj_sfv/component/CollectDialog.dart';
import 'package:proj_sfv/http/api.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:proj_sfv/main.dart';
import 'package:proj_sfv/store/MyAppState.dart';
import 'package:video_player/video_player.dart';
import '../domain/Video.dart';
import 'package:http/http.dart' as http;

import 'CommentPopup.dart';


class MyVideoPlayer extends StatefulWidget {
  final Video video;
  String token;
  int id;
  MyAppState state;
  MyVideoPlayer(this.video, this.token, this.id, this.state); // MyVideoPlayer({video , super.key});


  @override
  State<StatefulWidget> createState() => _MyVideoPlayer();
}

class _MyVideoPlayer extends State<MyVideoPlayer> {
   VideoPlayerController _controller;
   Future<void> _videoPlayerFuture;
  var _play = false;
  bool _isLike = false;
  bool _isCommentPopup = false;
  bool _isDislike = false;
  bool _isCollected = false;
  bool _isFollow = false;

  var id;
  var token;
  var videoId;

  void pressPlay() {
    setState(() {
      if (_controller.value.isPlaying) {
        _play = true;
        _controller.pause();
      } else {
        _play = false;
        _controller.play();
      }
    });
  }

  @override
  void initState() {
    super.initState();
    if (widget.video.videoUrl != null) {
      _controller = VideoPlayerController.network(widget.video.videoUrl);
      _videoPlayerFuture = _controller.initialize();
    }
    _videoPlayerFuture.whenComplete(() {
      _controller.play();
    });
    if (widget.id != 0 && widget.token != "") {
      if (widget.video.videoId != "0") {
        setState(() {
          id = widget.id;
          token = widget.token;
          videoId = widget.video.videoId;
        });
        // 判断是否喜欢视频
        isLike();
        isDislike();
        isCollected();
        isFollow();
      }
    }
  }

  void isFollow() async {
    if (id != widget.video.authorId) {
      var resp = await getUserRelationRequest(context, id, token, widget.video.authorId);
      if (resp != null) {
        setState(() {
          _isFollow = resp[1];
        });
      }
    }
  }

  void isLike() async {
    var resp = await getIsLikeVideoRequest(context, widget.id, widget.token, widget.video.videoId);
    if (resp != null) {
      setState(() {
        _isLike = resp;
      });
    }
  }

  void isDislike() async {
    var resp = await getIsDislikeVideoRequest(context, widget.id, widget.token, widget.video.videoId);
    if (resp != null) {
      setState(() {
        _isDislike = resp;
      });
    }
  }

  void isCollected() async {
    bool result = await getIsCollectVideoRequest(context, widget.id, widget.token, widget.video.videoId);
    if (result != null) {
      setState(() {
        _isCollected = result;
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  void changeLike(bool isLike) {
      if (widget.id != 0) {
        if (isLike == false) {
          likeVideoRequest(context, id, token, videoId, VideoPreference.LIKE).then((value) {
            if (value != null) {
              Fluttertoast.showToast(msg: "点赞成功");
              setState(() {
                _isLike = !_isLike;
                widget.video.likeCount++;
              });
            }
          });
        } else {
           cancelLikeVideoRequest(context, id, token, videoId, VideoPreference.LIKE).then((value) {
             if (value != null) {
               Fluttertoast.showToast(msg: "取消点赞成功");
               setState(() {
                 _isLike = !_isLike;
                 widget.video.likeCount--;
               });
             }
           });
        }
      } else {
        Fluttertoast.showToast(msg: "请先登陆");
      }
  }

  void changeDislike(bool isDislike) {
    if (widget.id != 0) {
      if (!isDislike) {
        likeVideoRequest(context, widget.id, widget.token, widget.video.videoId,
            VideoPreference.DISLIKE).then((value) {
          if (value != null) {
            Fluttertoast.showToast(msg: "点踩成功");
            setState(() {
              _isDislike = !_isDislike;
            });
          }
        });
      } else {
        cancelLikeVideoRequest(context, id, token, videoId, VideoPreference.DISLIKE).then((value) {
          if (value != null) {
            setState(() {
              _isDislike = !isDislike;
            });
          }
        });
      }
    } else {
      Fluttertoast.showToast(msg: "请先登陆");
    }
  }

  void getCommentTree(int page) {
    // 这里发送请求
    store.dispatch(SystemActions.HideNavigateBar);
    setState(() {
      _isCommentPopup = !_isCommentPopup;
    });
    Scaffold.of(context).showBottomSheet<void>((context) {
      return CommentPopup(videoId, id, token);
    }).closed.whenComplete(() {
      store.dispatch(SystemActions.HideNavigateBar);
      setState(() {
        _isCommentPopup = false;
        widget.state.navigateBarHidden = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    var authorNameStyle = new TextStyle(color: Colors.white54, fontWeight: FontWeight.bold, fontSize: 27.0);
    return Scaffold(
      backgroundColor: Colors.black,
      body: StoreConnector<MyAppState, bool> (
        converter: (store) => store.state.navigateBarHidden,
        builder: (context, flag) {
          return Stack(
            children: [
              FutureBuilder(
                future: _videoPlayerFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    return Container(
                      padding: flag ? EdgeInsets.only(bottom: 500) : EdgeInsets.zero,
                      child: Center(
                        child: GestureDetector(
                          onTap: pressPlay,
                          child: AspectRatio(
                            aspectRatio: _controller.value.aspectRatio,
                            child: VideoPlayer(
                              _controller,
                            ),
                          ),
                        ),
                      ),
                    );
                  } else {
                    // If the VideoPlayerController is still initializing, show a
                    // loading spinner.
                    return const Center(
                      child: CircularProgressIndicator(),
                    );
                  }
                },
              ),
              Container(
                padding: flag ? EdgeInsets.only(bottom: 500) : EdgeInsets.zero,
                child: Center(
                  child: Visibility(
                    visible: _play,
                    child: FloatingActionButton(
                      backgroundColor: Colors.transparent,
                      foregroundColor: Colors.transparent,
                      onPressed: pressPlay,
                      child: Icon(
                        Icons.play_arrow,
                        color: Colors.white54,
                      ),
                    ),
                  ),
                ),
              ),
              Align(
                alignment: Alignment.bottomRight,
                child: VideoButtonBar(
                  _isLike,
                  _isDislike,
                  _isCollected,
                  changeLike,
                  changeDislike,
                  getCommentTree,
                    () { setState(() {
                        _isCollected = true;
                    });},
                   _isCommentPopup,
                  widget.video,
                  id,
                  token
                ),
              ),
              Positioned(
                bottom: 40,
                left: 0,
                child: DefaultTextStyle(
                  style: TextStyle(color: Colors.white54, fontSize: 20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            '@${widget.video.userVo.userName?? widget.video.authorId}',
                            style: authorNameStyle,
                          ),
                          SizedBox(width: 5,),
                          id != widget.video.authorId ? ElevatedButton(
                            style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.pink)),
                            onPressed: () async {
                              if (_isFollow) {
                                var result = await unfollowUserRequest(context, id, token, widget.video.authorId);
                                if (result != null) {
                                  setState(() {
                                    _isFollow = false;
                                  });
                                }
                              } else {
                                var result = await followUserRequest(context, id, token, widget.video.authorId);
                                if (result != null) {
                                  setState(() {
                                    _isFollow = true;
                                  });
                                }
                              }
                            },
                            child: Row(
                              children: [
                                Icon(Icons.add),
                                Text(_isFollow ? "取消关注" : "关注"),
                              ],
                            ),
                          ) : Container()
                        ],
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 20),
                        child: Text(
                          widget.video.videoName,
                          textAlign: TextAlign.left
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 20),
                        child: Text(
                          widget.video.tags,
                          textAlign: TextAlign.left,
                        ),
                      )
                    ],
                  ),
                ),
              )
            ],
          );
        }
      ),
    );
  }
}

class VideoButtonBar extends StatelessWidget {

   VideoButtonBar(
     bool isLike,
      bool isDislike,
      bool isCollected,
     this.changeLikeImpl,
    this.changeDislikeImpl,
     this.getCommentImpl,
     this.changeCollectImpl,
     bool isCommentPopup,
     Video video,
       this.id,
       this.token
  ) : _isLike = isLike, _isCommentPopup = isCommentPopup, _video = video, _isDislike = isDislike,
         _isCollected = isCollected;

   bool _isLike;
   bool _isDislike;
   bool _isCollected;

   bool _isCommentPopup;
   Video _video;
  var changeLikeImpl;
  var changeDislikeImpl;
  var getCommentImpl;
  var changeCollectImpl;

  int id;
  String token;

  void changeLike() {
    changeLikeImpl(_isLike);
  }

  void changeDislike () {
    changeDislikeImpl(_isDislike);
  }

  void changeCollect() {
    changeCollectImpl();
  }

  void getComment() {
    getCommentImpl(1);
  }

  @override
  Widget build(BuildContext context) {
    var themeData = Theme.of(context).buttonTheme.copyWith(textTheme: ButtonTextTheme.primary);
    return ButtonBar(
        buttonPadding: EdgeInsets.only(bottom: 20),
        buttonHeight: 60,
        buttonMinWidth: 60,
        children: [Column(
          mainAxisAlignment: MainAxisAlignment.end,
          // mainAxisSize: MainAxisSize.max,
          children: [
            MaterialButton(
              textColor: Colors.white,
              textTheme: ButtonTextTheme.primary,
                onPressed: changeLike,
                child: Column(
                  children: [
                    Icon(Icons.favorite, color: _isLike ? Colors.red : Colors.white54,),
                    Text(_video.likeCount.toString())
                  ],
                )
            ),
            MaterialButton(
                textColor: Colors.white,
                textTheme: ButtonTextTheme.primary,
                onPressed: changeDislike,
                child: Column(
                  children: [
                    Icon(Icons.thumb_down_alt , color: _isDislike ? Colors.red : Colors.white54 ),
                  ],
                )
            ),
            MaterialButton(
                onPressed: getComment, 
                child: Icon(Icons.comment, color: _isCommentPopup ? Colors.red : Colors.white54,)
            ),
            MaterialButton(
              onPressed: () async {
                String collectName  = await showDialog(context: context, builder: (context) => ChooseBookmarkDialog(id, token));
                if (collectName == null) {
                  return;
                }
                var resp = await addNewCollectItem(context, id, token, collectName, _video.videoId);
                if (resp != null) {
                  Fluttertoast.showToast(msg: "添加收藏成功");
                  changeCollectImpl();
                }
              },
              child: Icon(Icons.star, color: _isCollected ? Colors.red : Colors.white54)),
            // MaterialButton(onPressed: () => {}, child: Icon(Icons.share, color: Colors.white54,),),
          ],
        ),]
    );
  }
}